@page "/checkout"
@inject OrderState OrderState
@inject HttpClient HttpClient
@inject IUriHelper UriHelper
@inject IJSRuntime JSRuntime

<div class="main">
    <AuthorizeView Context="authContext">
        <NotAuthorized>
            <h2>Redirecting you...</h2>
        </NotAuthorized>
        <Authorized>
            <EditForm Model="@OrderState.Order.DeliveryAddress" OnValidSubmit="@PlaceOrder">
                <div class="checkout-cols">
                    <div class="checkout-order-details">
                        <h4>Review order</h4>
                        <OrderReview Order="@OrderState.Order" />
                    </div>

                    <div class="checkout-delivery-address">
                        <h4>Deliver to...</h4>
                        <AddressEditor Address="@OrderState.Order.DeliveryAddress" />
                    </div>
                </div>

                <button type="submit" class="checkout-button btn btn-warning" disabled="@isSubmitting">
                    Place order
                </button>

                <DataAnnotationsValidator />
            </EditForm>
        </Authorized>
    </AuthorizeView>
</div>

@functions {
    bool isSubmitting;
    [CascadingParameter] Task<AuthenticationState> AuthenticationStateTask { get; set; }

    protected override async Task OnInitAsync()
    {
        var authState = await AuthenticationStateTask;
        if (!authState.User.Identity.IsAuthenticated)
        {
            // The server won't accept orders from unauthenticated users, so avoid
            // an error by making them log in at this point
            await LocalStorage.SetAsync(JSRuntime, "currentorder", OrderState.Order);
            UriHelper.NavigateTo("user/signin?redirectUri=/checkout", true);
        }

        // Try to recover any temporary saved order
        if (!OrderState.Order.Pizzas.Any())
        {
            var savedOrder = await LocalStorage.GetAsync<Order>(JSRuntime, "currentorder");
            if (savedOrder != null)
            {
                OrderState.ReplaceOrder(savedOrder);
                await LocalStorage.DeleteAsync(JSRuntime, "currentorder");
            }
            else
            {
                // There's nothing check out - go to home
                UriHelper.NavigateTo("");
            }
        }
    }

    async Task PlaceOrder()
    {
        isSubmitting = true;

        try
        {
            var newOrderId = await HttpClient.PostJsonAsync<int>("orders", OrderState.Order);
            OrderState.ResetOrder();
            UriHelper.NavigateTo($"myorders/{newOrderId}");
        }
        finally
        {
            isSubmitting = false;
        }
    }
}
